package edu.neu.cs6515.xml.converter;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import edu.neu.cs6515.xml.Board;
import edu.neu.cs6515.xml.Score;
import edu.neu.cs6515.xml.Tile;
import edu.neu.cs6515.xml.w12.XMLTurn;

public class TurnConverter implements Converter {

    @Override
    public boolean canConvert(final Class type) {
        return XMLTurn.class.equals(type);
    }

    @Override
    public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
        XMLTurn turn = (XMLTurn) source;
        Board board = turn.getBoard();
        writer.startNode("board");
        context.convertAnother(board);
        writer.endNode();
        Score s = turn.getScore();
        writer.startNode("score");
        context.convertAnother(s);
        writer.endNode();
        List<Tile> tiles = turn.getTile();
        for (Tile tile : tiles) {
            writer.startNode("tile");
            context.convertAnother(tile);
            writer.endNode();
        }
    }

    @Override
    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        XMLTurn turn = new XMLTurn();
        reader.moveDown();
        Board board = (Board) context.convertAnother(turn, Board.class);
        turn.setBoard(board);
        reader.moveUp();
        reader.moveDown();
        Score score = (Score) context.convertAnother(turn, Score.class);
        turn.setScore(score);
        reader.moveUp();
        List<Tile> tiles = new ArrayList<Tile>();
        while (reader.hasMoreChildren()) {
            TileConverter tc = new TileConverter();
            reader.moveDown();
            Tile tile = (Tile) tc.unmarshal(reader, context);
            reader.moveUp();
            tiles.add(tile);
        }
        turn.setTile(tiles);
        return turn;
    }
}
